package com.wx.wxsecondskill.service;

import static com.wx.wxsecondskill.controller.SecondsKillController.USERSECONDSKILREFIX;
import static com.wx.wxsecondskill.enums.SecondsKillEnumStatus.OrderChannelStatus.ORDER_CHANNEL_STATUS_1;
import static com.wx.wxsecondskill.enums.SecondsKillEnumStatus.OrderStatus.ORDER_STATUS_1;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wx.redis.RedisUtils;
import com.wx.wxsecondskill.dao.OrderDao;
import com.wx.wxsecondskill.po.OrderInfo;
import com.wx.wxsecondskill.po.SecondsKillOrder;
import com.wx.wxsecondskill.po.User;
import com.wx.wxsecondskill.vo.GoodsVo;

/**
 * @ClassName SecondsKillService
 * @Author wx
 * @Description 订单业务层
 * @Date 2018-11-15-22:17
 */
@Service
public class OrderService {

	@Autowired
	private OrderDao orderDao;

	public SecondsKillOrder getMiaoshaOrderByUserIdGoodsId(String userId, Integer goodsId) {
		return orderDao.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
	}

	@Transactional
	public OrderInfo createOrder(User user, GoodsVo goods) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setCreateDate(new Date());
		orderInfo.setDeliveryAddrId(222);
		orderInfo.setGoodsCount(1);
		orderInfo.setGoodsId(goods.getId());
		orderInfo.setGoodsName(goods.getGoodsName());
		orderInfo.setGoodsPrice(goods.getSecondsKillPrice());
		orderInfo.setOrderChannel(ORDER_CHANNEL_STATUS_1.getCode());
		orderInfo.setStatus(ORDER_STATUS_1.getCode());
		orderInfo.setUserId(user.getId());
		orderDao.insert(orderInfo);
		SecondsKillOrder miaoshaOrder = new SecondsKillOrder();
		miaoshaOrder.setGoodsId(goods.getId());
		miaoshaOrder.setOrderId(orderInfo.getId());
		miaoshaOrder.setUserId(user.getId());
		orderDao.insertMiaoshaOrder(miaoshaOrder);
		return orderInfo;
	}


	/**
	 * @methodName: userIsSecondsKillGoods
	 * @author: wx
	 * @description: 验证用户是否秒杀过该商品
	 * @param userId 用户id
	 * @param goodsId 商品id
	 * @date: 2018/11/19
	 * @return: SecondsKillOrder
	 */
	public SecondsKillOrder userIsSecondsKillGoods(String userId, Integer goodsId) {
		SecondsKillOrder secondsKillOrder =  (SecondsKillOrder)RedisUtils.redisClient.get(USERSECONDSKILREFIX + userId + "-" + goodsId);
		return  secondsKillOrder;
	}
}
